<template>
  <div class="editForm">
    <div>
      <div class="role-assignment-wrap assignment-wrap">
        <SelfAdaption>
          <Form
            :model="formSearch"
            ref="userFormSearch"
            slot="adaption-bar"
            label-position="top"
            class="ivu-form-no-margin-bottom"
            inline
          >
            <template>
              <Form-item class="user-roles-label" :label="$t('module.userManage.userRoles')">
                <Select v-model="devRoleCode" v-if="type == 'dev'"  disabled>
                  <Option v-for="item in devRoleList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
                <Select v-else v-model="formSearch.roleCode"  disabled>
                  <Option v-for="item in roleList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
              </Form-item>
            </template>
          </Form>
        </SelfAdaption>
      </div>
      <div class="role-assignment-wrap assignment-wrap">
        <SelfAdaption>
          <Form
            :model="formSearch"
            ref="userFormSearch"
            slot="adaption-bar"
            label-position="top"
            class="ivu-form-no-margin-bottom"
            inline
          >
            <template>
              <!-- 用户账号 -->
              <Form-item prop="userId" class="user-account-label" :label="$t('module.userManage.userAccount')">
                <Input
                  type="text"
                  v-model.trim="formSearch.userId"
                  :placeholder="$t('module.userManage.placeholder.account')"
                  @on-enter="searchInfo"
                ></Input>
              </Form-item>

              <!-- 用户名称 -->
              <Form-item prop="userName" :label="$t('module.userManage.name')">
                <Input
                  type="text"
                  v-model.trim="formSearch.userName"
                  :placeholder="$t('module.userManage.placeholder.userName')"
                  @on-enter="searchInfo"
                  :maxlength="30"
                ></Input>
              </Form-item>

              <!-- 手机号码 -->
              <Form-item prop="mobile" :label="$t('module.userManage.cellPhoneNumber')">
                <Input
                  type="text"
                  v-model.trim="formSearch.mobile"
                  :placeholder="$t('module.userManage.placeholder.phoneNumber')"
                  @on-enter="searchInfo"
                  :maxlength="11"
                ></Input>
              </Form-item>

              <!-- 电子邮箱 -->
              <Form-item prop="email" :label="$t('module.userManage.email')">
                <Input
                  type="text"
                  v-model.trim="formSearch.email"
                  :placeholder="$t('module.userManage.placeholder.email')"
                  @on-enter="searchInfo"
                ></Input>
              </Form-item>

              <!-- 查询\重置按钮 -->
              <Form-item prop="button" class="search-solt-btn">
                <RPButton optType="search" @click="searchInfo" />
                <RPButton optType="reset" @click="formReset" />
              </Form-item>
            </template>
          </Form>
        </SelfAdaption>
        <div style="padding: 20px 0; height: 388px;">
          <InnerPageTable ref="tenantTable" :config="tableConfig"> </InnerPageTable>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import locales from "./locales.js";
import { queryUnAssignedUser, assignUser, getRoleByRoleCode } from "@/api/teantManageAPI.js";
import { tenantColumns } from "./columns.js";
import { CoreModuleName } from "@/const";
import { getDevelopUserList, authorizationToUser } from "@/api/orgApi";

export default {
  components: {},
  props: {
    tenantCode: {
      type: String,
      required: true
    },
    type: {
      type: String,
      required: ''
    }
  },
  mixins: [locales],
  data() {
    return {
      formSearch: {
        userId: "",
        userName: "",
        mobile: "",
        email: "",
        category: 2,
        tenantCode: this.tenantCode,
        excludeAuthorizedUsersByTenant: true,
        roleCode: "admin-tenant"
      },
      categoryList: [
        {
          value: 1,
          label: this.$t("module.userManage.platformAdmin") //平台管理员
        },
        {
          value: 2,
          label: this.$t("module.userManage.tenantAdmin") // 租户管理员
        },
        {
          value: 3,
          label: this.$t("module.userManage.ordinaryUser") // 普通用户
        },
        {
          value: 4,
          label: this.$t("module.userManage.developerUser") // 普通用户
        }
      ],
      devRoleCode: "developer",
      roleList: [],
      devRoleList: [{
          value: 'developer',
          label: '开发者'
        }],
      tableSelection: [],
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {
    tableConfig() {
      return {
        loadDataFn: this.type == 'dev' ? this.getDevAssignUser : this.getUnAssignUser,
        columnsFn: tenantColumns.bind(this),
        onSelectionChange: this.selection
        // initParam: this.formSearch
      };
    }
  },
  created: function () {
    this.init();
    this.$emit("SetTitle", this.$t("module.tenantManage.assignUser"));
    this.$emit("SetPageWidth", 734);
    // this.$emit("SetPageMinHeight", 200);
    this.$emit("SetPageActions", this.actions);
  },
  mounted() {
    this.search();
  },
  methods: {
    init() {
      // 获取角色
      getRoleByRoleCode(this.formSearch.roleCode).then(({ roleCode, roleName }) => {
        if (roleCode) {
          this.roleList.push({
            value: roleCode,
            label: roleName
          });
        }
      });
    },
    selection(tableVal) {
      this.tableSelection = [];
      tableVal.forEach(item => {
        this.tableSelection.push(item.id);
      });
    },
    assignUser() {
      // 批量
      if (this.tableSelection.length == 0) {
        this.$message.error({
          content: this.$t("common.warning.selctAddElement"),
          duration: 3
        });
        return;
      }
      this.actions[0].loading = true;
      let param = {
        roleCode: "admin-tenant",
        tenantCode: this.tenantCode,
        userIds: this.tableSelection
      };
      assignUser(param)
        .then(() => {
          this.$message.success({
            content: this.$t("common.addSuccess"),
            duration: 3
          });
          this.actions[0].loading = false;
          this.$emit("Close", true);
        })
        .catch(() => {
          this.actions[0].loading = false;
        });
    },
    deleteAdmin() {},
    searchInfo() {
      this.search();
    },
    formReset() {
      this.$refs["userFormSearch"].resetFields();
      this.search();
    },
    devAssignUser() {
      let param = {
        roleCode: "developer",
        tenantCode: this.tenantCode,
        userIds: this.tableSelection
      };
      if(this.tableSelection.length == 0) {
        this.$message.error({
          content: this.$t("common.warning.selctAddElement"),
          duration: 3
        });
        return
      }
      this.actions[0].loading = true
      authorizationToUser(param).then(res => {
          this.$message.success({
          content: this.$t("module.tenantManage.success.syncSuccess"),
          duration: 3
          });
          this.actions[0].loading = false
          this.$emit("Close", true);
      })
    },
    save() {
      if(this.type == 'dev') {
        this.devAssignUser()
      } else {
        this.assignUser();
      }
    },
    getUnAssignUser({ responseProcess, param }) {
      queryUnAssignedUser(param).then(data => {
        responseProcess(data.data);
      });
    },
    getDevAssignUser({ responseProcess, param }) {
      // const form = {
      //       "commonPageDTO": param.commonPageDTO || {},
      //       "sortDTO": {
      //           "fieldName": "",
      //           "orderBy": ""
      //       },
      //       "pageNum": param.pageNum || 1,
      //       "pageSize": param.pageSize || 10,
      //       "tenantCode": this.tenantCode,
      //       "excludeAuthorizedUsersByTenant": true,
      //       "condition": {
      //           "tenantCode": this.tenantCode,
      //           "excludeAuthorizedUsersByTenant": true
      //       }
      //   }
      getDevelopUserList(param).then(data => {
        responseProcess(data.data);
      });
    },
    search(page = 1) {
      this.$refs["tenantTable"].load(this.formSearch, page);
    }
  },
  watch: {},
  directives: {}
};
</script>
<style lang="less">
  .assignment-wrap {
    .ivu-form-item-label {
      min-width: 55px !important;
    }
  }
</style>
